package com.pox.guli.common.base.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.springframework.util.StringUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @Author PoX21s
 * @Date: 2022/6/5 20:20
 * @Version 1.0
 */

public class JwtUtils {

    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    private static Key getKeyInstance() {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary(APP_SECRET);

        return new SecretKeySpec(bytes, signatureAlgorithm.getJcaName());
    }

    public static String getJwtToken(JwtInfo jwtInfo, int expire) {

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("guli-user") // 主题
                .setIssuedAt(new Date()) // 颁发时间
                .setExpiration(DateTime.now().plusSeconds(expire).toDate()) // 过期时间
                .claim("id", jwtInfo.getId()) // 用户id
                .claim("nickname", jwtInfo.getNickname()) // 用户昵称
                .claim("avatar", jwtInfo.getAvatar()) // 用户头像
                .signWith(SignatureAlgorithm.HS256, getKeyInstance())
                .compact();
    }

    /**
     * 判断token是否有效
     *
     * @param jwtToken token判断
     */
    public static boolean checkJwtTToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) return false;

        try {
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 判断token有效时间
     *
     * @param request 请求的有效性
     */
    public static boolean checkJwtTToken(HttpServletRequest request) {

        try {
            String jwtToken = request.getHeader("token");
            if (StringUtils.isEmpty(jwtToken)) return false;

            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }

        return true;
    }

    /**
     * 根据token获取会员id
     *
     * @param request 请求
     */
    public static JwtInfo getMemberIdByJwtToken(HttpServletRequest request) {

        String jwtToken = request.getHeader("token");

        if (StringUtils.isEmpty(jwtToken)) return null;

        Jws<Claims> claimsJws = Jwts.parser()
                .setSigningKey(getKeyInstance())
                .parseClaimsJws(jwtToken);

        Claims claims = claimsJws.getBody();

        return new JwtInfo(claims.get("id").toString(),
                claims.get("nickname").toString(),
                claims.get("avatar").toString());
    }
}
